package com.rerun.common.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;


/**
 * <p>
 * ehcache 缓存工具类
 * </p>
 * <p>
 * cacheName在ehcache.xml中配置
 * </p>
 */
public class EhcacheHelper {

    /**
     * The constant CACHE_MANAGER.
     */
    private static final CacheManager CACHE_MANAGER = CacheManager.create();


    private EhcacheHelper() {
    }

    /**
     * Get object.
     *
     * @param cacheName the cache name
     * @param key       the key
     * @return the object
     */
    public static Object get(String cacheName, Object key) {
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        if (cache != null) {
            Element element = cache.get(key);
            if (element != null) {
                return element.getObjectValue();
            }
        }
        return null;
    }

    private static void addCache(String cacheName) {
        if (!CACHE_MANAGER.cacheExists(cacheName)) {
            CACHE_MANAGER.addCache(cacheName);
        }
    }

    /**
     * Put.
     *
     * @param cacheName the cache name
     * @param key       the key
     * @param value     the value
     */
    public static void put(String cacheName, Object key, Object value) {
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        if (cache == null) {
            addCache(cacheName);
            cache = CACHE_MANAGER.getCache(cacheName);
        }
        cache.put(new Element(key, value));
    }

    public static String[] getCacheNames() {

        return CACHE_MANAGER.getCacheNames();
    }

    /**
     * Remove boolean.
     *
     * @param cacheName the cache name
     * @param key       the key
     * @return the boolean
     */
    public static boolean remove(String cacheName, Object key) {
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        return cache != null && cache.remove(key);
    }

}
